package com.vitas.coin.ui.fm

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.media3.common.Player
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.snap.base.util.BaseUtil
import com.snap.base.util.BaseUtil.postEvent
import com.snap.common.main.BaseFg
import com.vitas.coin.R
import com.vitas.coin.data.bean.ChildrenVoiceBean
import com.vitas.coin.data.bean.MusicType
import com.vitas.coin.data.event.ContentEvent
import com.vitas.coin.data.event.FavorEvent
import com.vitas.coin.data.event.ListEvent
import com.vitas.coin.data.event.PausePlayEvent
import com.vitas.coin.data.event.PlayEvent
import com.vitas.coin.data.event.StartPlayEvent
import com.vitas.coin.databinding.FragmentToolsBinding
import com.vitas.coin.db.PlayDao
import com.vitas.coin.db.TypeDao
import com.vitas.coin.manager.PlayManager
import com.vitas.coin.resp.CollectDaoResp
import com.vitas.coin.ui.act.FavorListAct
import com.vitas.coin.ui.act.ListAct
import com.vitas.coin.ui.adapter.TypeListAdapter
import com.vitas.coin.ui.dialog.DetailJumper
import com.vitas.coin.ui.dialog.NewListDlg
import com.vitas.coin.util.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class ListFrag : BaseFg(), DetailJumper {

    lateinit var binding: FragmentToolsBinding
    private val collectDaoResp by lazy { CollectDaoResp }
    var h = Handler(Looper.getMainLooper())
    val gson = Gson()
    var list: ArrayList<MusicType>? = null
    var adapter: TypeListAdapter? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentToolsBinding.inflate(inflater, container, false)
        binding.tvCreate.setOnClickListener {
            NewListDlg().setOnDismissListener<NewListDlg> { isOk, value ->
                if (isOk && value is String) {
                    list?.let {
                        var type = MusicType(value.toString())
                        GlobalScope.launch {
                            TypeDao().insert(type)
                            h.post {
                                it.add(type)
                                adapter?.notifyItemInserted(it.size - 1)
                                postEvent(ListEvent())
                            }
                        }
                    }
                }
            }.show(childFragmentManager, "")
        }
        binding.rvList.layoutManager =
            LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false)
        binding.tvRecently.setOnClickListener {
            var i = Intent(requireActivity(), FavorListAct::class.java)
            i.putExtra("from", 1)
            startActivity(i)
        }
        binding.tvOften.setOnClickListener {
            var i = Intent(requireActivity(), FavorListAct::class.java)
            i.putExtra("from", 2)
            startActivity(i)
        }

        initObserve()
        initBottomPlay()
        getList()
        getFavor()
        getPlayNum()

        return binding.root
    }

    private fun initBottomPlay() {
        val playStatus = PlayManager.getInstance().playStatus
        if (playStatus == Player.STATE_IDLE) {
            binding.clBottom.visibility = View.GONE
        } else {
            binding.clBottom.visibility = View.VISIBLE
            binding.tvMusicName.text = PlayManager.getInstance().musicName
            if (PlayManager.getInstance().isPlaying) {
                binding.ivPlay.setImageResource(R.mipmap.icon_pause)
            } else {
                binding.ivPlay.setImageResource(R.mipmap.icon_start)
            }
        }
        binding.ivPlay.setOnClickListener {
            PlayManager.getInstance().onClickPlayButton()
        }
        binding.ivShoucangList.setOnClickListener {
            PlayManager.getInstance().showList(requireActivity())
        }
    }

    private fun initObserve() {
        BaseUtil.observer(this, ListEvent::class.java) {
            getList()
        }
        BaseUtil.observer(this, FavorEvent::class.java) {
            getFavor()
        }
        BaseUtil.observer(this, ContentEvent::class.java) {
            updateContent(it.id)
        }
        BaseUtil.observer(this, PlayEvent::class.java) {
            getPlayNum()
        }
        BaseUtil.observer(this, StartPlayEvent::class.java) {
            if (binding.clBottom.visibility == View.GONE) {
                binding.clBottom.visibility = View.VISIBLE
            }
            binding.tvMusicName.text = it.musicObj.musicName
            binding.ivPlay.setImageResource(R.mipmap.icon_pause)
        }

        BaseUtil.observer(this, PausePlayEvent::class.java) {
            binding.ivPlay.setImageResource(R.mipmap.icon_start)
        }
    }

    fun updatePlayNum(i: Long) {
        binding.tvRecentlyCount.text = i.toString()
    }

    fun updateContent(id: String) {
        GlobalScope.launch {
            list?.let {
                for (item in it) {
                    if (item.id.equals(id)) {
                        item.list = Utils.getContent(id)
                        h.post {
                            adapter?.notifyItemChanged(it.indexOf(item))
                        }
                        break
                    }
                }
            }
        }
    }

    fun getList() {
        GlobalScope.launch {
            list = Utils.getList()
            h.post {
                adapter = TypeListAdapter(this@ListFrag, requireActivity(), list)
                binding.rvList.adapter = adapter
            }
        }
    }

    fun getFavor() {
        GlobalScope.launch {
            var tmp = withContext(Dispatchers.IO) {
                collectDaoResp.queryAll()
            }
            h.post {
                binding.tvLoveCount.text = tmp.size.toString()
                binding.tvLove.setOnClickListener {
                    var i = Intent(requireActivity(), FavorListAct::class.java)
                    if (tmp is ArrayList) {
                        i.putParcelableArrayListExtra("list", tmp)
                    } else {
                        var list = ArrayList<ChildrenVoiceBean>()
                        list.addAll(tmp)
                        i.putParcelableArrayListExtra("list", list)
                    }
                    startActivity(i)
                }
            }
        }
    }

    fun getPlayNum() {
        GlobalScope.launch {
            var dao = PlayDao()
            val num = dao.allCaseNum()
            h.post {
                updatePlayNum(num)
            }
            var tmp = dao.always()
            h.post {
                updateAlways(tmp)
            }
        }
    }

    fun updateAlways(i: Long) {
        binding.tvOftenCount.text = i.toString()
    }

    override fun toList(page: Int) {
        if (list == null || list!!.size <= page) {
            return
        }
        var i = Intent(requireActivity(), ListAct::class.java)
        var tmp = list!![page]
        i.putExtra("data", tmp);
        startActivityForResult(i, 1)
    }
}
